import functions from "./functions";

export default {
  openFrame(url, options = {}) {
    const name = url.split("/").pop().slice(0, -5);
    let finalOptions = functions.extendObj({}, options);
    if (api.version) {
      api.openFrame({
        name,
        // pageParam:{
        //   name:"a",
        // },
        url,
        ...finalOptions,
      });
    } else {
      window.location.href = url;
    }
  },
  openFrameGroup(url, options = {}) {
    const name = url.split("/").pop().slice(0, -5);
    let finalOptions = functions.extendObj({}, options);
    if (api.version) {
      api.openFrameGroup({
        name,
        // pageParam:{
        //   name:"a",
        // },
        url,
        ...finalOptions,
      });
    } else {
      window.location.href = url;
    }
  },
  openWin(url, options = {}) {

    // var header,footer,headerH,footerH;
    // try {
    //   header = $api.dom("header"); // 获取 header 标签元素
    //   footer = $api.dom("footer"); // 获取 footer 标签元素
    //   headerH = $api.fixStatusBar(header);
    //   footerH = $api.fixTabBar(footer);
    // }catch (e) {
    //   headerH = footerH = 0;
    // }
    // console.log(`headerH,footerH:${headerH},${footerH}`);


    const name = url.split("/").pop().slice(0, -5);
    let finalOptions = functions.extendObj({
      singleInstance: true,// save window, improve UI & performance
      useWKWebView: true,// improve performance !!! except <= ios8.0
      bgColor: "#6a9fb5",
    }, options);
    if (api.version) {
      console.log("app open");
      api.openWin({
        ...finalOptions,
        name,
        url,
        // headerH,
        // footerH,
      });
    } else {
      console.log("web open");
      window.location.href = url;
    }
  },
  closeWin(options = {}) {

    let finalOptions = functions.extendObj({}, options);
    if (api.version) {
      api.closeWin({
        ...finalOptions,
      });
    } else {
      window.history(-1);
    }
  },
  closeToWin(name,options={}){
    let finalOptions = functions.extendObj({}, options);
    api.closeToWin({
      name,
      ...finalOptions,
    });
  },
  api(action, options = {}) {
    let finalOptions = functions.extendObj({}, options);
    return new Promise((resolve, reject) => {
      api[action]({
        success: resolve,
        fail: reject,
        ...finalOptions,
      });
    });
  },
  readFile(filename) {
    return new Promise((resolve, reject) => {
      api.readFile({sync: false, path: filename}, (ret, err) => {
        if (ret.status) {
          resolve(ret.data);
        } else {
          reject(err);
        }
      });
    });
  },
  writeFile(params) {
    return new Promise((resolve, reject) => {
      api.writeFile({
        ...params,
      }, (ret, err) => {
        let msg = "";
        if (ret.status) {
          resolve({status: ret.status, msg});
        } else {
          const errs = [
            "没有错误", "找不到文件错误", "不可读取错误", "编码格式错误", "无效操作错误", "无效修改错误", "磁盘溢出错误", "文件已存在错误",
          ];
          reject({status: false, msg: errs[err.code], code: err.code});
        }
      });
    });
  },
  readFileSync(filename) {
    return api.readFile({sync: true, path: filename});
  },
  setGlobalData(key, value) {
    return api.setGlobalData({key: key, value: value});
  },
  getGlobalData(key) {
    return api.getGlobalData({key: key});
  },
  getTemperature() {
    return this.getGlobalData("temperature");
  },
  setTemperature(temperature) {
    this.setGlobalData("temperature", temperature);
  },
  getPrefsSync(key) {
    return api.getPrefs({sync: true, key: key});
  },
  getPrefs(key) {
    return new Promise((resolve, reject) => {
      api.getPrefs({sync: false, key: key}, (ret, err) => {
        if (ret.status) {
          resolve(ret.data);
        } else {
          reject(err);
        }
      });
    });
  },
  getModule(name) {
    return api.require(name) || null;
  },
  setPrefs(key, value) {
    api.setPrefs({key: key, value: value});
  },
  removePrefs(key) {
    api.removePrefs({key: key});
  },
  // setRecordingStatus(val){
  //   this.setGlobalData("recordingStatus", val);
  // try{
  //   this.writeFile({path:"cache://blewendu_recordingstatus.txt",data:val,append:false});
  // }catch (e) {
  //   console.log(e);
  // }
  // },
  // getRecordingStatus(){
  //   return this.getGlobalData("recordingStatus") || 0;
  // return this.readFileSync("cache://blewendu_recordingstatus.txt") || 0;
  // },
  reloadFrame(){
    window.location.reload();
  },
  async getOAuth2token() {

    const beforeTime = 10000;
    const oauth_config = {
      client_id: "",
      client_secret: "",
      grant_types: "",
      redirect_uri: "",
      token_type: "",
      express_in: "",
      access_token: "",
      refresh_token: "",
      express_at: 0,
    };

    Object.keys(oauth_config).forEach(v => {
      oauth_config[v] = this.getPrefsSync(`oauth2.${v}`) || oauth_config[v];
    });

    if (oauth_config.client_id === "")
      return false;

    let t = new Date().getTime();
    if (parseInt(oauth_config.express_at) < t) {

      const {apiTokenFetch} = require("./requests");

      console.log(apiTokenFetch);

      try {

        let res = await apiTokenFetch(oauth_config.redirect_uri, oauth_config);
        this.setPrefs("oauth2.access_token", res.access_token);
        this.setPrefs("oauth2.express_in", res.express_in);
        this.setPrefs("oauth2.refresh_token", res.refresh_token || "");
        this.setPrefs("oauth2.token_type", res.token_type || "");
        this.setPrefs("oauth2.express_at", parseInt(res.express_in) * 1000 + t - beforeTime);

        return res.access_token;
      } catch (e) {
        this.setPrefs("local.isLogin",0);
        return false;
      }

    }
    return oauth_config.access_token;
  },
};

